package org.card.util;

import org.apache.commons.lang.math.NumberUtils;
import org.card.bean.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by card on 16/1/6.
 */
public class CookieUtils {

    private final static String prefix = "da#@I*O(";

    public static String getCookie(HttpServletRequest request, String name) {
        Cookie cookies[] = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void writeCookie(HttpServletResponse response, String name, String value, boolean save) {
        Cookie cookie = new Cookie(name, value);
        if(save) {
            cookie.setMaxAge(60 * 60 * 24 * 30);
        }
        response.addCookie(cookie);
    }

    public static boolean hasLogin(HttpServletRequest request) {
        String username = getCookie(request, "username");
        String token = getCookie(request, "token");

        if (username != null && token != null) {
            String t = MD5Utils.md5(prefix + username);
            return t.equalsIgnoreCase(token);
        }

        else {
            return false;
        }
    }

    public static void login(HttpServletResponse response, User user, boolean saveLogin){
        writeCookie(response, "userId", user.getId().toString(), saveLogin);
        writeCookie(response, "username", user.getUsername(), saveLogin);
        writeCookie(response, "token", MD5Utils.md5(prefix + user.getUsername()), saveLogin);
    }

    public static Integer getUserId(HttpServletRequest request){
        if (hasLogin(request)) {
            String userId = getCookie(request, "userId");
            if(NumberUtils.isNumber(userId)) {
                return NumberUtils.toInt(userId);
            }
        }
        return null;
    }

    public static String getUsername(HttpServletRequest request){
        if (hasLogin(request)) {
            return getCookie(request, "username");
        }
        return null;
    }
}
